package com.example.coursehub.course.entity;

import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 章节实体类
 * 改进了原有设计，添加了排序和审计字段
 */
@Getter
@Setter
@Entity
@Table(name = "chapter", schema = "courseHub")
@NoArgsConstructor
@AllArgsConstructor
@EntityListeners(AuditingEntityListener.class)
public class Chapter {
    
    @Id
    @Column(name = "chapter_id", nullable = false, length = 100)
    private String chapterId;

    @NotBlank(message = "章节名称不能为空")
    @Size(max = 100, message = "章节名称长度不能超过100个字符")
    @Column(name = "chapter_name", nullable = false, length = 100)
    private String chapterName;

    /**
     * 章节描述
     */
    @Size(max = 500, message = "章节描述长度不能超过500个字符")
    @Column(name = "chapter_description", length = 500)
    private String chapterDescription;

    /**
     * 章节排序号
     */
    @Column(name = "sort_order", nullable = false)
    private Integer sortOrder = 0;

    /**
     * 章节状态：0-草稿，1-发布
     */
    @Column(name = "status", nullable = false)
    private Integer status = 0;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @OnDelete(action = OnDeleteAction.CASCADE)
    @JoinColumn(name = "course_id", nullable = false)
    private Course course;

    @CreatedDate
    @Column(name = "created_at", nullable = false, updatable = false)
    private LocalDateTime createdAt;

    @LastModifiedDate
    @Column(name = "updated_at")
    private LocalDateTime updatedAt;

    /**
     * 章节资料（一对多关系）
     */
    @OneToMany(mappedBy = "chapter", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private List<Material> materials;

    /**
     * 章节状态枚举
     */
    public enum ChapterStatus {
        DRAFT(0, "草稿"),
        PUBLISHED(1, "已发布");

        private final Integer code;
        private final String description;

        ChapterStatus(Integer code, String description) {
            this.code = code;
            this.description = description;
        }

        public Integer getCode() {
            return code;
        }

        public String getDescription() {
            return description;
        }
    }
}